﻿using System.Collections.Generic;
using System.Linq;
using FazaDemo.BL.CM.CollectionMechanisms;

namespace FazaDemo.BL.Services_
{
    public class InfoListsProvider
    {

        private const string Field = "[FIELD]";

        private const string Mode = "[MODE]";

        private const string Semicolon = ";";

        private const string ScolonAfterWspace = " ;";

        private const string LineFeedChar = "\r\n";

        public IList<List<string>> GetInfoLists(string ecqText)
        {
            IEnumerable<string> fieldsInfosArea = CreateInfosArea(ecqText);
            return CreateInfoLists(fieldsInfosArea);
        }

        private IEnumerable<string> CreateInfosArea(string ecqText)
        {
            var curText = ecqText.Replace(Semicolon, ScolonAfterWspace);
            curText = curText.Replace(LineFeedChar, " ");
            var ecqCleanText = SplitAndFilter(curText, ' ', "");
            return ecqCleanText.SkipTakeWhile(t => t != Field, t => t != Mode).ToList();
        }

        private IList<List<string>> CreateInfoLists(IEnumerable<string> fieldsInfosArea)
        {
            var fieldsInfoLists = FillInfoLists(fieldsInfosArea);
            return CleanInfoLists(fieldsInfoLists);
        }

        private IList<List<string>> FillInfoLists(IEnumerable<string> fieldsInfosArea)
        {
            return fieldsInfosArea.Split(Field).ToList();
        }

        private IList<List<string>> CleanInfoLists(IList<List<string>> infoLists)
        {
            for (int i = 0; i < infoLists.Count; i++)
            {
                infoLists[i] = infoLists[i].Where(IsNotSeparator).ToList();
            }
            return infoLists;
        }

        private IEnumerable<string> SplitAndFilter(string text, char separator, string filter)
        {
            return text.Split(separator).Where(c => c != filter);
        }

        private bool IsNotSeparator(string t)
        {
            return !(t.Contains('/') && t.Contains('-') && t.Count(c => c == '-') > 10);
        }

    }
}
